import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rcmd/app/modules/rcmd/views/custom_cmd_page.dart';
import 'package:rcmd/app/modules/rcmd/views/inner_log_page.dart';
import 'package:rcmd/app/modules/rcmd/views/ip_cluster_cfg_page.dart';
import 'package:rcmd/app/utils/keep_alive_page.dart';

import '../ssh_service.dart';
import 'console_controller.dart';

class BaseController extends GetxController {}

class RcmdController extends GetxController {
  final pageSel = BaseController();
  final active = "".obs;
  PageController? pageController;
  final filter = "".obs;
  final pages = <List>[];
  final pageCount = 0.obs;

  @override
  void onReady() async {
    await Get.putAsync(() => SshService().init()).then((value) {
      SshService srv = Get.find();
      srv.updateSshCfg("172.24.37.159", "root", "ruijie1688", 9622);
      srv.updateSshCfg("172.24.37.20", "lzd", "lzd", 22);
    });
    pages.add(["", IpClusterCfgPage("")]);
    pageCount.value = 1;
    super.onReady();
  }

  @override
  void onInit() {
    pageController = PageController(initialPage: 0);
    super.onInit();
  }

  void _addPage(String title, Object page) {
    pages.add([title, keepAliveWrapper(page as Widget), page]);
    pageCount.value = pages.length;
    selectPage(title, isJmp: true);
  }

  void addCustomCmdPage(
      {List<String>? selIpList, ConsoleController? controller}) {
    var title = "命令" + pages.length.toString();
    final page = CustomCmdPage(title, selIpList: selIpList);
    if (controller != null) page.controller.copyDisplay(controller);
    _addPage(title, page);
  }

  void addInnerLogPage() {
    var title = "日志" + pages.length.toString();
    _addPage(title, InnerLogPage(title));
  }

  void removeCurrentPage() {
    int pos = (pageController?.page ?? 0.0).toInt();
    if (pos > 0) {
      pages[pos][1].wantKeepAlive = false;
      pages[pos][2].dispose();
      pages.removeAt(pos);
      if (pos >= pages.length) pos = pages.length - 1;
      selectPage(pages[pos][0], isJmp: true);
      pageCount.value = pages.length;
    } else {
      active.value = "";
    }
  }

  void selectPage(String title, {bool isJmp = false}) {
    active.value = title;
    pageSel.update();
    for (int pos = 1; pos < pages.length; pos++) {
      if (pages[pos][0] == title) {
        if (isJmp) {
          pageController?.jumpToPage(pos);
        } else {
          pageController?.animateToPage(pos,
              duration: Duration(milliseconds: 300), curve: Curves.easeInOut);
        }
        return;
      }
    }
    pageController?.jumpToPage(0);
  }

  ConsoleController? get activePage {
    if (active.value == "") return null;
    return pages
        .firstWhere((element) => element[0] == active.value)[2]
        .controller;
  }
}
